<template>
  <div class="login window">
    <div class="login-title drag">SheepppChat</div>
    <div v-if="showLoading" class="loading-box">
      <img src="../assets/images/loading.gif" alt="" />
    </div>
    <div v-else class="login-form">
      <div class="error-msg"></div>
      <el-form ref="formDataRef" :model="formData" :rules="rules">
        <el-form-item prop="email">
          <el-input v-model.trim="formData.email" clearable placeholder="请输入邮箱">
            <template #prefix>
              <span class="iconfont icon-mail"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" prop="nickName">
          <el-input v-model.trim="formData.nickName" clearable placeholder="请输入昵称">
            <template #prefix>
              <span class="iconfont icon-user"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model.trim="formData.password"
            show-password
            clearable
            placeholder="请输入密码"
          >
            <template #prefix>
              <span class="iconfont icon-mima"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin" prop="rePassword">
          <el-input
            v-model.trim="formData.rePassword"
            show-password
            clearable
            placeholder="再次输入密码"
          >
            <template #prefix>
              <span class="iconfont icon-mima"></span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <div class="captcha">
            <el-input v-model.trim="formData.captcha" clearable placeholder="请输入验证码">
              <template #prefix>
                <span class="iconfont icon-yanzhengma"></span>
              </template>
            </el-input>
            <img class="captcha-img" :src="captchaData" alt="" @click="changeCaptcha" />
          </div>
        </el-form-item>
        <el-form-item> </el-form-item>
        <el-form-item>
          <el-button class="login-btn" type="primary" @click="submit">{{
            isLogin ? '登录' : '注册'
          }}</el-button>
        </el-form-item>
        <div class="bottom-link">
          <el-button type="text" @click="changeLoginType">{{
            isLogin ? '没有账号？' : '已有账号？'
          }}</el-button>
        </div>
      </el-form>
    </div>
  </div>
  <WinOp :show-set-top="false" :show-min="false" :show-max="false" :close-type="0"></WinOp>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { passwordValidator } from '@/utils'
import Request from '@/utils/request'
import Api from '@/utils/api'
import Message from '@/utils/Message'
import useUserInfoStore from '@/store/userInfoStore'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const rules = reactive({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      validator: passwordValidator
    }
  ],
  rePassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: passwordValidator },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.password) {
          callback('两次输入的密码不一致')
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, message: '昵称长度不能小于2位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, message: '验证码长度不能小于4位', trigger: 'blur' }
  ]
})
const showLoading = ref(false)
const captchaData = ref('')
const formData = reactive({
  email: 'mail.sheeppp@qq.com',
  password: '123456',
  rePassword: '',
  nickName: '',
  captcha: ''
})

const isLogin = ref(true)
const formDataRef = ref(null)

onMounted(() => {
  changeCaptcha()
})

async function changeCaptcha() {
  captchaData.value = URL.createObjectURL(
    await Request({
      url: Api.captcha,
      responseType: 'blob'
    })
  )
}

function changeLoginType() {
  isLogin.value = !isLogin.value
  window.ipcRenderer.send('loginOrRegister', isLogin.value)
  changeCaptcha()
}

async function submit() {
  formDataRef.value.validate(async (valid) => {
    if (!valid) return

    const res = await Request({
      url: isLogin.value ? Api.login : Api.register,
      methods: 'POST',
      params: formData,
      showLoading: !isLogin.value
    })
    if (!res) return
    if (res.code === -1) {
      changeCaptcha()
      return Message.error(res.msg)
    }
    Message.success(res.msg)

    if (isLogin.value) {
      showLoading.value = true
      localStorage.setItem('token', res.data.token)
      const res2 = await Request({
        url: Api.userInfo + `/${formData.email}`,
        methods: 'GET',
        showLoading: false
      })
      userInfoStore.setUserInfo(res2.data)
      showLoading.value = true
      setTimeout(() => {
        router.replace('/main')
        window.ipcRenderer.send('openChat', {
          email: formData.email,
          token: res.data.token,
          userId: res2.data.id,
          nickName: res2.data.nickName
        })
      }, 1000)
    } else {
      setTimeout(() => {
        changeLoginType()
      }, 1000)
    }
  })
}
</script>

<style scoped lang="scss">
.loading-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 250px;
}
.login-title {
  font-size: 24px;
  margin-bottom: 16px;
  color: var(--base-color);
}
.login-btn {
  width: 100%;
}
.bottom-link {
  display: flex;
  justify-content: flex-end;
}
.captcha {
  display: flex;
}
.captcha-img {
  width: 100px;
  height: 34px;
}
</style>
